package com.jcp.baselibrary.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jcp.baselibrary.R;

import java.lang.ref.WeakReference;

/**
 * =========================================================
 *
 * @ProjectName:
 * @ClassName: ToastUtil
 * @Description:
 * @Author: jincp
 * @CreateDate: 2019/3/22 22:07
 * =========================================================
 */
public class ToastUtil {

    private static WeakReference<Context> context;
    private static ToastUtil instance;
    private Toast toast;

    public static ToastUtil getInstance() {
        if (instance == null || ToastUtil.context.get() == null) {
            instance = new ToastUtil();
        }
        return instance;
    }

    private ToastUtil() {
        ToastUtil.context = new WeakReference<>(UIUtils.getContext());
    }

    public void show(final String message) {
        try {
            if(TextUtils.isEmpty(message)){
                return;
            }
            if (toast == null) {
                View view = LayoutInflater.from(context.get()).inflate(R.layout.layout_toast, null);
                toast = new Toast(context.get());
                toast.setView(view);
            } else {
                View view = toast.getView();
                toast.cancel();
                toast= new Toast(context.get());
                toast.setView(view);
            }
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.setDuration(Toast.LENGTH_SHORT);
            TextView textView = (TextView) toast.getView().findViewById(R.id.toast_text);
            textView.setText(message);
            toast.show();
        } catch (Exception e){
            e.printStackTrace();
            reset();
        }
    }

    public void show(int resId) {
        show(UIUtils.getString(resId));
    }

    public void cancel() {
        if (toast != null) {
            toast.cancel();
        }
    }

    public void reset() {
        toast = null;
    }
}
